import React from "react";
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {url} from '../../util/config'

const request = {
    action: url.file_upload_url,
    headers: {
        'Accept': "application/json",
        'Authorization': localStorage.getItem("token")
    },
}

export default class PicturesWall extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            fileList: [],
        };
        console.log(this.props.defaultValue)
        if(this.props.defaultValue!=undefined){
            this.state.fileList.push(this.props.defaultValue)
        }
    }

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await this.getBase64(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };

    getBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }

    handleChange = ({ fileList }) => {
        if(fileList.length>0){
            if(fileList[0].status=="done"){
                this.props.render(fileList[0].response.result[0].FILE_URL)
            }
        }else if(fileList.length==0){
            this.props.render("")
        }
        this.setState({ fileList });

    }



    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        console.log(fileList)
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        return (
            <>
                <Upload
                    {...request}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    beforeUpload={this.beforeUpload}
                >
                    {fileList.length >= 1 ? null : uploadButton}
                </Upload>
            </>
        );
    }
}
